<template>
  <el-card class="page-container">
    <!-- 卡片头部 -->
    <template #header>
      <div class="header">
        <span>所有房源</span>
        <div class="extra">
          <!-- 添加房源按钮 -->
          <el-button type="primary" @click="dialogVisible = true; title = '添加房源'; clearData()">添加房源</el-button>
        </div>
      </div>
      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" style="margin-top: 20px;">
        <el-row :gutter="10">
          <!-- 客户名称搜索 -->
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-select
                  v-model="searchForm.customerId"
                  placeholder="请选择客户"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in CusListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 房东名称搜索 -->
          <el-col :span="6">
            <el-form-item label="房东名称">
              <el-select
                  v-model="searchForm.landlordId"
                  placeholder="请选择房东"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in LanListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 中介名称搜索 -->
          <el-col :span="6">
            <el-form-item label="中介名称">
              <el-select
                  v-model="searchForm.intermediaryId"
                  placeholder="请选择中介"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in IntListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 小区名称搜索 -->
          <el-col :span="6">
            <el-form-item label="小区名称">
              <el-select
                  v-model="searchForm.communityId"
                  placeholder="请选择小区"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in ComListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 居室描述搜索 -->
          <el-col :span="6">
            <el-form-item label="居室描述" prop="description">
              <el-select
                  v-model="searchForm.description"
                  placeholder="请输入居室描述"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in housewearOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 房屋状态搜索 -->
          <el-col :span="6">
            <el-form-item label="房屋状态" prop="description">
              <el-select v-model="searchForm.status" placeholder="请输入居室描述">
                <el-option label="待审核" value="0" />
                <el-option label="已发布" value="1" />
                <el-option label="已下架" value="2" />
                <el-option label="已成交" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 搜索按钮 -->
          <el-col :span="2">
            <el-button type="primary" @click="housesList">搜索</el-button>
          </el-col>
          <!-- 重置按钮 -->
          <el-col :span="2">
            <el-button type="primary" @click="clearsearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <!-- 房源列表 -->
    <el-table :data="houseListData" style="width: 100%" v-loading="loading">
      <el-table-column label="序号" width="50" type="index" />
      <el-table-column label="房东" prop="landlordName" />
      <el-table-column label="客户" prop="customerName" />
      <el-table-column label="中介" prop="intermediaryName" />
      <el-table-column label="面积">
        <template #default="{ row }">
          {{ row.area }}㎡
        </template>
      </el-table-column>
      <el-table-column label="价格">
        <template #default="{ row }">
          ¥{{ row.price.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="居室描述" prop="descriptionName" width="130" />
      <el-table-column label="地址" prop="address" />
      <el-table-column label="小区" prop="communityName" />
      <el-table-column label="类型">
        <template #default="{ row }">
          <el-tag :type="row.type === '0'? '' :'success'">
            {{ row.type === '0'? '卖房' : '租房' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-tag
              :type="{
              0: 'warning',
              1:'success',
              2: 'info',
              3: ''
            }[row.status]"
          >
            {{
              {
                0: '待审核',
                1: '已发布',
                2: '已下架',
                3: '已成交'
              }[row.status]
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布日期" prop="publishTime" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <!-- 查看操作按钮 -->
          <el-button
              :icon="Document"
              circle
              plain
              type="info"
              @click="handleView(row)"
          />
          <!-- 编辑操作按钮 -->
          <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="showDeit(row)"
          />
          <!-- 删除操作按钮 -->
          <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无房源数据" />
      </template>
    </el-table>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="40%">
      <el-form :model="HousesModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <!-- 房东名称选择 -->
        <el-form-item label="房东名称" prop="landlordId">
          <el-select
              v-model="HousesModel.landlordId"
              placeholder="请选择房东"
              clearable
              filterable
          >
            <el-option
                v-for="item in LanListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 客户名称选择 -->
        <el-form-item label="客户名称">
          <el-select
              v-model="HousesModel.customerId"
              placeholder="请选择客户"
              clearable
              filterable
          >
            <el-option
                v-for="item in CusListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 小区名称选择 -->
        <el-form-item label="小区名称" prop="communityId">
          <el-select
              v-model="HousesModel.communityId"
              placeholder="请选择小区"
              clearable
              filterable
          >
            <el-option
                v-for="item in ComListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 居室描述选择 -->
        <el-form-item label="居室描述" prop="description">
          <el-select
              v-model="HousesModel.description"
              placeholder="请选择居室"
              clearable
              filterable
          >
            <el-option
                v-for="item in housewearOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 房屋地址输入 -->
        <el-form-item label="房屋地址" prop="address">
          <el-input v-model="HousesModel.address" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <!-- 房屋面积输入 -->
        <el-form-item label="房屋面积" prop="area">
          <el-input v-model="HousesModel.area" minlength="1" maxlength="15"></el-input>
        </el-form-item>
        <!-- 房屋价格输入 -->
        <el-form-item label="房屋价格" prop="price">
          <el-input v-model="HousesModel.price" minlength="1" maxlength="15"></el-input>
        </el-form-item>
        <!-- 委托类型选择 -->
        <el-form-item label="委托类型" prop="type">
          <el-select v-model="HousesModel.type" placeholder="请选择类型">
            <el-option label="卖房" value="0" />
            <el-option label="租房" value="1" />
          </el-select>
        </el-form-item>
        <!-- 房屋状态选择 -->
        <el-form-item label="房屋状态" prop="status">
          <el-select v-model="HousesModel.status" placeholder="请选择状态">
            <el-option label="待审核" value="0" />
            <el-option label="已发布" value="1" />
            <el-option label="已下架" value="2" />
            <el-option label="已成交" value="3" />
          </el-select>
        </el-form-item>
        <!-- 中介名称选择 -->
        <el-form-item label="中介名称">
          <el-select
              v-model="HousesModel.intermediaryId"
              placeholder="请选择中介"
              clearable
              filterable
          >
            <el-option
                v-for="item in IntListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <!-- 取消按钮 -->
          <el-button @click="dialogVisible = false">取消</el-button>
          <!-- 确认按钮 -->
          <el-button type="primary" @click="title === '添加房源'? addHouse() : updataHouse()"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

    <router-view></router-view>

  </el-card>

</template>

<script setup>
import { Edit, Delete, Document } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { addHouseService, housesListService, updateHouseService, deleteHouseService } from '@/api/housesList.js'
import { getHousewearList } from '@/api/housewear'
import { getLanList, getIntList, getCusList } from "@/api/user.js";
import { getCommunityList } from '@/api/community.js';
import { ElMessage, ElMessageBox } from "element-plus";

// 房源列表数据
const houseListData = ref([])
// 弹窗标题
const title = ref('')
// 控制添加/编辑弹窗显示
const dialogVisible = ref(false)
// 房源表单数据
const HousesModel = ref({
  id: '',
  landlordId: '',
  address: '',
  customerId: '',
  area: '',
  price: '',
  description: '',
  type: '',
  status: '',
  communityId: '',
  intermediaryId: '',
  landlordName: '',
  intermediaryName: '',
  communityName: '',
  descriptionName: '',
  customerName: ''
})
// 表单校验规则
const rules = {
  address: [
    { required: true, message: '地址不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (/\s/.test(value)) {
          callback(new Error('地址不能包含空格'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  area: [
    { required: true, message: '面积不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^\d+(\.\d+)?$/.test(value)) {
          callback(new Error('请输入有效数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  price: [
    { required: true, message: '价格不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^\d+(\.\d+)?$/.test(value)) {
          callback(new Error('请输入有效数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 下拉选项数据
const housewearOptions = ref([])
const LanListOptions = ref([])
const ComListOptions = ref([])
const IntListOptions = ref([])
const CusListOptions = ref([])

// 分页数据
const pageNum = ref(1) // 当前页
const total = ref(0) // 总条数
const pageSize = ref(15) // 每页条数

// 搜索条件
const searchForm = ref({
  customerId: '',
  landlordId: '',
  intermediaryId: '',
  communityId: '',
  description: '',
  area: '',
  price: '',
  status: ''
})

// 每页条数变化时重新获取数据
const onSizeChange = (size) => {
  pageSize.value = size
  housesList()
}
// 当前页码变化时重新获取数据
const onCurrentChange = (num) => {
  pageNum.value = num
  housesList()
}

// 加载状态
const loading = ref(false)

// 获取房源列表
const housesList = async () => {
  try {
    loading.value = true
    const result = await housesListService({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchForm.value
    })
    if (result && result.res) {
      houseListData.value = result.res.items
      total.value = result.res.total
    } else {
      console.error('接口返回数据格式不正确，缺少 data 属性')
      ElMessage.error('加载房源列表失败，接口返回数据格式不正确')
    }
  } catch (error) {
    console.error('数据获取失败:', error)
    ElMessage.error('加载房源列表失败')
  } finally {
    loading.value = false
  }
}

// 清空搜索条件并重新获取数据
const clearsearch = () => {
  searchForm.value = {
    customerId: '',
    landlordId: '',
    intermediaryId: '',
    communityId: '',
    description: '',
    area: '',
    price: '',
    status: ''
  }
  housesList()
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const reshouse = await getHousewearList()
    housewearOptions.value = reshouse.res.map(item => ({
      value: item.id,
      label: item.houseType
    }))
    const resLan = await getLanList()
    LanListOptions.value = resLan.res.map(item => ({
      value: item.id,
      label: item.nickname
    }))
    const resCom = await getCommunityList()
    ComListOptions.value = resCom.res.map(item => ({
      value: item.id,
      label: item.name
    }))
    const resint = await getIntList()
    IntListOptions.value = resint.res.map(item => ({
      value: item.id,
      label: item.nickname
    }))
    const rescus = await getCusList()
    CusListOptions.value = rescus.res.map(item => ({
      value: item.id,
      label: item.nickname
    }))
  } catch (error) {
    console.error('获取失败:', error)
    ElMessage.error('加载失败')
  }
}

// 处理空值转换
const handleNullValues = (data) => {
  return {
    ...data,
    customerId: data.customerId || null,
    intermediaryId: data.intermediaryId || null
  }
}

// 添加房源
const addHouse = async () => {
  const submitData = handleNullValues(HousesModel.value)
  await addHouseService(submitData)
  ElMessage.success('添加成功')
  housesList()
  dialogVisible.value = false
  clearData()
}

// 显示编辑弹窗
const showDeit = (row) => {
  dialogVisible.value = true
  title.value = '修改房源'
  HousesModel.value = {
    id: row.id,
    landlordId: row.landlordId,
    address: row.address,
    customerId: row.customerId,
    area: row.area,
    price: row.price,
    description: row.description,
    type: row.type,
    status: row.status,
    communityId: row.communityId,
    intermediaryId: row.intermediaryId
  }
}

// 编辑房源
const updataHouse = async () => {
  const submitData = handleNullValues(HousesModel.value)
  await updateHouseService(submitData)
  ElMessage.success('修改成功')
  housesList()
  dialogVisible.value = false
  clearData()
}

// 清空表单数据
const clearData = () => {
  HousesModel.value = {
    id: '',
    landlordId: '',
    address: '',
    customerId: '',
    area: '',
    price: '',
    description: '',
    type: '',
    status: '',
    communityId: '',
    intermediaryId: ''
  }
}

// 删除房源
const handleDelete = (row) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteHouseService(row.id)
    housesList()
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 查看操作
const router = useRouter()
const handleView = (row) => {
  router.push({
    name: 'housesItemDetail',
    params: { id: row.id },
    query: { from: 'housesManagement' } // 添加来源标识
  })
}

// 初始化数据
fetchDropdownOptions()
housesList()
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
  //background-color: #f0f0f0; /* 添加灰色背景颜色 */

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .el-tag {
    margin: 2px;
  }
}

:deep(.el-table) {
  border-radius: 8px; /* 给表格添加圆角 */
  overflow: hidden; /* 确保内容不会溢出圆角 */
}

:deep(.el-input__inner) {
  border-radius: 8px; /* 给输入框添加圆角 */
}

:deep(.el-table__cell) {
  .cell {
    white-space: nowrap;
  }
}
</style>
